﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.EntityClient;
using System.Data.Objects;
using System.Data;

namespace Httlgd.DataCenter.Services.Core
{
    public class ObjectContextBase : System.Data.Objects.ObjectContext
    {
        public ObjectContextBase(string connectionString, string defaultContainerName)
            : base(connectionString, defaultContainerName)
        {
            this.SavingChanges += new EventHandler(ObjectContextBase_SavingChanges);
        }

        public ObjectContextBase(EntityConnection connection, string defaultContainerName)
            : base(connection, defaultContainerName)
        {
            this.SavingChanges += new EventHandler(ObjectContextBase_SavingChanges);
        }


        void ObjectContextBase_SavingChanges(object sender, EventArgs e)
        {
            IEnumerable<ObjectStateEntry> changes = this.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified);

            foreach (ObjectStateEntry entry in changes)
            {
                if (entry.Entity is EntityBase)
                {
                    EntityBase ent = entry.Entity as EntityBase;
                    ent.SetLastUpdateDate();                    
                    if (entry.State == EntityState.Added) { ent.SetCreateDate(); }
                }
            }
        }
    }
}
